<template>
  <div class="member-management">
    <!-- 新增会员按钮 -->
    <el-button type="primary" size="large" @click="openAddMemberDialog" style="margin-bottom: 20px;">新增会员</el-button>
    <el-tabs type="border-card" v-model="data.activeTab" v-loading="data.loading">
      <el-tab-pane label="会员中心" name="overview">
        <MemberOverview :data="data.summaryData" @viewDetail="showMemberDetails" />
        <ConsumptionTrend :data="data.trendData" v-if="isDataReady" />
      </el-tab-pane>

      <el-tab-pane label="会员列表" name="trend">
        <el-table :data="date.data" style="width: 100%; margin-top: 20px;" :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold' }">
          <el-table-column prop="name" label="名字" width="180"></el-table-column>
          <el-table-column prop="rechargeAmount" label="充值金额" width="180"></el-table-column>
          <el-table-column prop="lv" label="会员等级" width="180"></el-table-column>
          <el-table-column prop="responsible" label="负责人" width="180"></el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" type="primary" @click="showMemberDetails(scope.row.id)">详情</el-button>
              <el-button size="small" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
              <el-button size="small" type="primary" @click="handleRecharge(scope.row.id)">充值</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="会员体系" name="vip">
        <VipConfig :data="data.vipLevels" @edit="handleEditLevel" @delete="handleDeleteLevel" />
      </el-tab-pane>
    </el-tabs>

    <MemberDetailDialog
      v-if="data.selectedMember"
      v-model="data.isDetailVisible"
      v-loading="data.isDetailVisible"
      :member="mockMemberData"
      @update="refreshData"
    />
    <Recharge
  v-if="isRechargeDialogVisible"
  v-model="isRechargeDialogVisible"
  :member-id="currentMemberId"
  @recharged="recharged"
/>
    <!-- 新增会员对话框 -->
    <AddMemberDialog
      v-if="isAddMemberDialogVisible"
      v-model="isAddMemberDialogVisible"
      @addMember="addMember"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect } from 'vue';
import { ElLoading } from 'element-plus';
import { Get_vip_Tolist } from '@/api/customerVip/index';
import MemberOverview from '@/components/CustomerVip/MemberOverview.vue';
import ConsumptionTrend from '@/components/CustomerVip/ConsumptionTrend.vue';
import VipConfig from '@/components/CustomerVip/VipConfig.vue';
import MemberDetailDialog from '@/components/CustomerVip/MemberDetailDialog.vue';
import AddMemberDialog from '@/components/CustomerVip/AddMemberDialog.vue';
import Recharge from '@/components/CustomerVip/Recharge.vue';
import { Get_vip_single, Get_vip_Order, Get_Level, Vip_Consumption, Get_vip, add_vip, del_vip } from '@/api/customerVip/index';
import { ElMessageBox } from 'element-plus';

const date = reactive({
  isFirst: true,
  data: [],
  Products: [],
  loading: false,
  key: "",
  details_key: "",
  details_key_id: "",
  pages: {
    page: 1,
    limit: 10,
    total: 0,
  },
});
const isAddMemberDialogVisible = ref(false);
// 模拟数据
const mockSummaryData = ref({
  count: 0,
  newMembersThisMonth: 0,
  money: 0,
  addmonth: 0
});
const mockTrendData = {
  monthlyGrowth: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  revenueBreakdown: { 戴宗瀚: 60, consume: 35, gift: 5 }
};
const confirmDelete = async (id: string) => {
  try {
    await ElMessageBox.confirm('确认要删除该会员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    // 用户点击了确定，执行删除操作
    await deleteMember(id);
  } catch (e) {
    // 用户点击了取消，不执行删除操作
    console.log('删除操作已取消');
  }
};
// 在script setup中添加
const isRechargeDialogVisible = ref(false)
const currentMemberId = ref('')

const handleRecharge = (id: string) => {
  currentMemberId.value = id
  isRechargeDialogVisible.value = true
}
const deleteMember = async (id: string) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在删除会员...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  const res = await del_vip({
    id,
  });
  if (res.code === 0) {
    await methods.bind();
    await methods.bind2();
    await methods.bind3();
    await methods.bind4();
    await methods.bind5();
  }
  loadingInstance.close();
};
const addMember = async (newMember) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在添加会员...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  try {
    // 假设这里有一个新增会员的 API 方法，需要根据实际情况替换
    const res = await add_vip(newMember);
    if (res.code === 0) {
      console.log('会员添加成功');
      // 刷新会员列表
      await methods.bind();
      await methods.bind2();
      await methods.bind3();
      await methods.bind4();
      await methods.bind5();
      // 关闭新增会员对话框
      isAddMemberDialogVisible.value = false;
    } else {
      console.error('会员添加失败', res.message);
    }
  } catch (error) {
    console.error('请求出错', error);
  }
  loadingInstance.close();
};
const isDataReady = ref(false);
const methods = {
  async bind5() {
    date.loading = true;
    const res = await Get_vip();
    if (res.code === 0) {
      date.data = res.data.data;
    }
    date.loading = false;
  },
  async bind() {
    date.loading = true;
    isDataReady.value = false;
    const res = await Get_vip_Tolist();
    if (res.code === 0) {
      mockSummaryData.value = res.data.data[0];
    }
    date.loading = false;
  },
  async bind2() {
    date.loading = true;
    const res2 = await Get_Level();
    if (res2.code === 0) {
      mockVipLevels.value = res2.data.data;
    }
    date.loading = false;
  },
  // 修改bind3方法中的数据处理逻辑
  async bind3() {
    date.loading = true;
    const res3 = await Vip_Consumption();
    if (res3.code === 0) {
    // 初始化空数组保证数据结构
    mockTrendData.monthlyGrowth = new Array(12).fill(0);

    // 添加空值检查和容错处理
    if (res3.data?.monthlyGrowth && typeof res3.data.monthlyGrowth === 'object') {
      // 遍历所有月份确保数据完整
      for (let month = 1; month <= 12; month++) {
        const value = res3.data.monthlyGrowth[month] || 0;
        mockTrendData.monthlyGrowth[month - 1] = Number(value);
      }
    }
  }
  date.loading = false;
  },
  async bind4() {
    date.loading = true;
    const res = await Get_vip();
    if (res.code === 0) {
      mockTrendData.revenueBreakdown = res.data.resultDate;
      isDataReady.value = true;
    }
    date.loading = false;
  }
};


watchEffect(() => {
  methods.bind();
  methods.bind2();
  methods.bind3();
  methods.bind4();
  methods.bind5();
});
const recharged =()=>{
  methods.bind();
  methods.bind2();
  methods.bind3();
  methods.bind4();
  methods.bind5();
  isRechargeDialogVisible.value=false
}
const openAddMemberDialog = () => {
  isAddMemberDialogVisible.value = true;
};

const mockVipLevels = ref([{
  id: '',
  name: '',
  discount: 0,
  count: 0,
  rechargeAmount: 0,
  consumptionAmount: 0,
  lv: ''
}]);

const mockMemberData = ref({
  id: "",
  name: "",
  registrationDate: "",
  contact: "",
  rechargeAmount: 0,
  consumptionAmount: 0,
  giftAmount: "",
  orders: [],
  rechargeHistory: [],
  discount: 0,
  count: 0,
  lv: ""
});

const data = reactive({
  loading: false,
  activeTab: 'overview',
  summaryData: mockSummaryData,
  trendData: mockTrendData,
  vipLevels: mockVipLevels,
  selectedMember: mockMemberData,
  isDetailVisible: false,
  detailLoading: false
});

const showMemberDetails = async (id: string) => {
  data.isDetailVisible = true;
  data.detailLoading = true;
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载会员详情...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  const res = await Get_vip_single({
    id: id
  });
  if (res.code === 0) {
    mockMemberData.value = res.data.data[0];
    mockMemberData.value.rechargeHistory = res.data.data2;
  }
  const res2 = await Get_vip_Order({
    id: id
  });
  if (res2.code === 0) {
    mockMemberData.value.orders = res2.data.data;
  }
  data.detailLoading = false;
  loadingInstance.close();
};

const handleEditLevel = (level: any) => {
  console.log('编辑会员等级:', level);
};

const handleDeleteLevel = (id: string) => {
  console.log('删除会员等级:', id);
};

const refreshData = () => {
  console.log('数据刷新');
};
methods.bind();
</script>

<style scoped>
.member-management {
  padding: 30px;
  background-color: #f9fafb;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.el-tabs__header {
  margin-bottom: 30px;
}

.el-tabs__nav-wrap::after {
  height: 2px;
  background-color: #e5e7eb;
}

.el-tabs__item {
  font-size: 18px;
  color: #6b7280;
  transition: color 0.3s ease;
}

.el-tabs__item.is-active {
  color: #3b82f6;
  font-weight: bold;
}

.el-tabs__content {
  padding: 30px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.el-button {
  border-radius: 4px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table__header th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
}

.el-table__body td {
  border-bottom: 1px solid #e5e7eb;
}
</style>



